import json
import re

import jsonpath

"""
filename
    method:
        operationId
        summary
        tags
        description
        parameters: []
        responses:
            200: {}
            400: {}
    parameters: 
"""


def schema_ref(items, schema):
    if schema.get('$ref'):
        ref = schema.get('$ref')
        ref = ref.replace('#', '$').replace('/', '.')
        schema = jsonpath.jsonpath(items, ref)

    return schema


def swagger2py(body: dict, api_dir, test_dir):
    body['tags'] = ['api', 'auth']
    # for tag in body['tags']:
    head = 'import json\nimport settings\n\n\n'
    results = {}

    test_head = 'import pytest\n\n\n'
    head_content = ''

    # items = []

    # 解析 paths
    # for (k, v) in body['paths'].items():
    #     for l in v.values():
    #         if tag['name'] in l['tags']:
    #             items.append(k)

    for item, value in body['paths'].items():

        for method in body['paths'][item]:
            if 'parameters' in method:
                continue

            filename = ''
            fun_name = set(re.sub(r'\/\{\w+\}', '', item.strip('/')).split('/'))
            fun_name = '_'.join(fun_name)
            fun_name = 'test_' + fun_name + '_' + method

            print('item:', item)
            print('fun_name:', fun_name)

            if fun_name[0] == '_':
                fun_name = fun_name[1:]

            params = get_api_param(body['paths'][item][method])
            description = ''

            if 'description' in body['paths'][item][method]:
                description = body['paths'][item][method]['description']

            url = item
            tag = method.split('/')[0]

            headers = get_api_header(body)
            fun_method = re.sub(r'\{\d+\}', '', method)

            reverse = body['paths'][item][method]
            responses = body['paths'][item][method]['responses']
            parameters = body['paths'][item][method]['parameters']

            # content += template.template(fun_name, params, description, url, headers, fun_method)
            # head_content += template.case_template(tag, fun_name, params, description, api_dir)

            # print(fun_method)
            # print(method)
            # print(headers)
            # print(reverse)
            # print(responses)
            # print(parameters)

            results[filename] = value

        print('=======================================================')
        # print("common.generate_file(api_dir, tag, head + content)")
        # exit()

        # if test_dir:
        #     common.generate_file(test_dir, 'test_' + tag['name'], test_head + head_content)


def get_swagger(path):
    with open(path, 'r', encoding='UTF-8') as postman_f:
        result_dict = json.load(postman_f)
        return result_dict


def get_api_param(item):
    if 'parameters' in item:
        return list(item['parameters'])

    return []


def get_api_header(item):
    result = {}

    if 'consumes' in item:
        result.setdefault("Content-Type", item['consumes'][0])

    return result
